package tom.webmvc.service;

import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Set;

/**
 * @author ZHUFEIFEI
 */
@Slf4j
@Service
public class SseService {

    private Set<SseEmitter> emitters = Sets.newConcurrentHashSet();


    public void add(SseEmitter sseEmitter) {
        sseEmitter.onCompletion(() -> {log.info("message send completion");this.emitters.remove(sseEmitter);});
        sseEmitter.onError((exp) -> {log.error(exp.getMessage());this.emitters.remove(sseEmitter);});
        sseEmitter.onTimeout(() -> log.warn("request timeout"));
        this.emitters.add(sseEmitter);
    }

    public void sendMsg(String msg) {
        this.emitters.forEach(sse ->{
            log.info("send msg : {} ", msg);
            try {
                sse.send(SseEmitter.event()
                        .id("eventId")
                        .name("stringEvent")
                        //指定重试时间，就是客户端重新连接的间隔
                        .reconnectTime(15 * 1000L)
                        .comment("this is comment").data(msg).build());
            } catch (IOException e) {
                this.emitters.remove(sse);
                log.error("send Exception!", e);
            }
        });
    }
}
